#!/usr/bin/env python
#
# Copyright (C) 2007 Rico Schiekel (fire at downgra dot de)
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# vim:syntax=python:sw=4:ts=4:expandtab

# first try psyco
try:
    import psyco
    psyco.full()
except ImportError:
    pass

import sys, os
import subprocess, atexit
import logging, logging.handlers

# init logger
logging.basicConfig(level=logging.WARN,
                    format='%(asctime)s %(levelname)s: %(name)s: %(message)s',
                    filename=os.path.expanduser('~/.wmii3.log'),
                    filemode='w')
logger = logging.getLogger('wmiirc')

WMII_CONFPATH = os.environ.get('WMII_CONFPATH', []).split(':')[0]

# define plan9 file system mount point
if not 'PLAN9_FS_MOUNT_POINT' in os.environ:
    os.environ.setdefault('PLAN9_FS_MOUNT_POINT', os.path.join(WMII_CONFPATH, 'fs'))

from config import *
# try to set log level
try:
    logging.getLogger().setLevel(LOG_LEVEL)
except:
    pass

from utils import *
init_tag_mappings(TAG_MAPPING)

from utils.statusbar import *
from events import *

# check wmii font
font_check = subprocess.Popen(['xlsfonts', '-fn', FONT], 
                              stdin = subprocess.PIPE, 
                              stdout = subprocess.PIPE, 
                              stderr = subprocess.PIPE, 
                              close_fds = True)
(fc_out, fc_err) = font_check.communicate()
if fc_err:
    FONT = '-*-fixed-medium-r-*-*-13-*-*-*-*-*-*-*'

# close running wmiirc
p9_write('/event', 'Start wmiirc')

# write base settings
p9_write('/ctl', (
    'font %s' % FONT,
    'focuscolors %s' % FOCUS_COLORS,
    'normcolors %s' % NORMAL_COLORS,
    'border %s' % BORDER,
    'grabmod %s' % MODKEY))

p9_write('/colrules', COL_RULES)
p9_write('/tagrules', TAG_RULES)
p9_write('/keys', EventResolver.used_keys())

# init statusbar
start_statusbar(os.path.join(WMII_CONFPATH, 'statusbar'),
                STATUS_BAR_SEPARATOR, \
                STATUS_BAR_START, \
                STATUS_BAR_END)
atexit.register(stop_statusbar)

# init event handler
atexit.register(stop_event_handler)
add_event(autostart)

# main loop
cont = True
while cont:
    try:
        p9_process('/event', add_event)
        cont = False
    except Exception, e:
        logger.exception(e)

logger.debug('safe shutdown')
